package org.wenhua.yuan.and.module_flutter.flutterM2

import android.app.Activity
import android.content.Context
import android.util.Log
import io.flutter.embedding.android.FlutterFragment
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugin.common.MethodChannel

object FlutterUtil  {
    fun createFragment (context: Context, name:String, route:String = "/fragment_dou") : FlutterFragment {
        val id = "fragment_${name}"
        var  flutterEngine = FlutterEngineCache.getInstance().get(id)

        if (flutterEngine == null) {
            flutterEngine = FlutterEngine(context)
            // 配置传入初始化路由信息，然后在flutter中通过window.defaultRouteName获取
            flutterEngine.navigationChannel.setInitialRoute(route)
            flutterEngine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault())

            FlutterEngineCache.getInstance().put(id, flutterEngine)
            setMethodChannel (context, flutterEngine)
        }

        return FlutterFragment.withCachedEngine(id)
            .shouldAttachEngineToActivity(true)
            .build()
    }

    private fun setMethodChannel(context: Context, flutterEngine: FlutterEngine) {
        MethodChannel(flutterEngine.dartExecutor, "common_channel")
            .setMethodCallHandler { call, result ->
                Log.d("flutter-debug", call.method)
                when (call.method) {
                    "closeCamera" -> closeCamera(context)
                    else -> result.notImplemented()
                }
            }
    }

    private fun closeCamera(context:Context) {
        Log.d("flutter-debug", "<<<===closeCamera===>>>")
        if (context is Activity) {
//            context.closeCamera()
        }
    }

}